package SortAlgorithmPractice;

import java.util.Arrays;

public class HeapSort {
    public static void main(String[] args) {
        int[] arr = {3,1,5,6,9,7,8,10};
        System.out.printf("Sort before : %s\n", Arrays.toString(arr));
        heapSort(arr);
        System.out.printf("Sort after : %s\n", Arrays.toString(arr));
    }

    public static void heapSort(int[] arr) {
        int n = arr.length;

        for (int i = n/2 - 1; i >= 0 ; i--) {
            heapify(arr, n, i);
        }
        // 一个个从堆顶取出元素
        for (int i = n - 1; i > 0 ; i--) {
            // 将当前最大的元素arr[0]和arr[i]交换
            int temp = arr[0];
            arr[0] = arr[i];
            arr[i] = temp;
            // 调整堆
            heapify(arr, i, 0);
        }
    }

    public static void heapify(int[] arr, int n, int i){
        int largest = i;
        int left = 2*i + 1;
        int right = 2*i + 2;

        if(left < n && arr[left] > arr[largest]){
            largest = left;
        }

        if(right < n && arr[right] > arr[largest]){
            largest = right;
        }

        if(largest != i){
            int swap = arr[i];
            arr[i] = arr[largest];
            arr[largest] = swap;
            heapify(arr, n, largest);
        }
    }
}
